<?php
/*
 * Created on 22.5.2006
 */
 
// TODO : je3t2 to nejsp93 ned2l8 XHTML dobrotu

class pStructure_Sumarize extends cGadget 
{	
	public $physic = false;

	function getXHTML() 
	{
		$this->sum = array();
		
		$source = $this->outSXML->xpath('//'.$this->getAttr('source'));

		$source = str_replace("<?xml version=\"1.0\"?>","",$source[0]);
		$dom = DOMDocument::loadXML('<content>'.(string)$source.'</content>');
		
		$header = $this->getElementsByIds($dom->documentElement, array('h1','h2','h3','h4','h5','h6'));
		
		$lastNum = 1;
		
		foreach ($header as $k=>$h) 
		{
			$id = $this->node->toSafeChars($h->nodeValue);
			$h->setAttribute('id',$id);
			
			$number = $h->tagName[1];
			
			if ($lastNum<$number) {
				$this->sum[] = '<ul>';
				$this->sum[] = str_repeat('<li><ul>',$number-$lastNum-1);
				$opened += $number-$lastNum; 
			} else if ($lastNum>$number) {
				$this->sum[] = str_repeat('</ul></li>',$lastNum-$number);
				$opened -= $lastNum-$number;				
			} 

			if ($lastNum==$number && $k>0) {
				$this->sum[]='</li>';
			}			

			//if ($k==count($header)-1) $this->sum[]='</li>';

			$lastNum = $number;
			$this->sum[] = '<li><a href="#'.$id.'">'.$h->nodeValue.'</a>';
		}
		
		$this->sum[] = str_repeat('</li></ul>',$opened);
		
		$root = $this->outSXML->xpath('/*');
		
		$sourcePath = explode('/',$this->getAttr('source'));
		
		$destination = array_pop($sourcePath);
		
		$sParent = $this->outSXML->xpath('//'.implode('/',$sourcePath));
		
		
		$s = $dom->saveXML();
		
		// when using DOMDocument, empty pair tag will become non-pair
		$s = preg_replace("/<div([^\/<>]*)\/>/","<div\\1></div>", $s);		
		
		$content = substr($s,strpos($s,'<content>')+9,-11);
		
		$sParent[0]->{$destination} = $content;
		
		return '<ul class="'.$this->tagName.'">'.implode("\n",$this->sum).'</li></ul>';
	}
	
	function getElementsByIds($el, $array) 
	{
		$ret = array();
		$array = array_flip($array);
		do {
			if (isset($array[$el->tagName])) {
				$ret[]=$el;
			}
		} while ($el = $this->next($el));
		return $ret;
	}
	
	function next($el) 
	{
		if ($el->hasChildNodes()) return $el->childNodes->item(0);
		if ($el->nextSibling!==null) return $el->nextSibling;
		while ($el->nextSibling===null && $el->parentNode!==null) {
			$el = $el->parentNode;
		}
		return $el->nextSibling;		
	}
	
}
 
?>